const config = require("../config")
const logger = require("../utils/logger")
const mysqlUtil = require("../utils/mysqlUtil")
const commonModule = require("./common")
const utils = require("../utils/util")

const moment = require('moment')

async function getLingdao(uid) {
    let sql = `
        SELECT
            con_department.zhijie_lingdao,
            tb_user_zhijie.name zhijie_lingdao_name,
            con_department.fenguan_lingdao,
            tb_user_fenguan.name fenguan_lingdao_name,
            con_department.zhuyao_lingdao,
            tb_user_zhuyao.name zhuyao_lingdao_name
        FROM
            tb_user
        INNER JOIN con_department ON con_department.id = tb_user.department
        LEFT JOIN tb_user tb_user_zhijie ON tb_user_zhijie.uid = con_department.zhijie_lingdao
        LEFT JOIN tb_user tb_user_fenguan ON tb_user_fenguan.uid = con_department.fenguan_lingdao
        LEFT JOIN tb_user tb_user_zhuyao ON tb_user_zhuyao.uid = con_department.zhuyao_lingdao
        WHERE tb_user.uid = ? LIMIT 1
    `

    let res = await mysqlUtil.execute(sql, [uid])
    return res[0] || null
}

async function getDepartmentLingdao(departId) {
    let sql = `
        SELECT
            con_department.zhijie_lingdao,
            tb_user_zhijie.name zhijie_lingdao_name,
            con_department.fenguan_lingdao,
            tb_user_fenguan.name fenguan_lingdao_name,
            con_department.zhuyao_lingdao,
            tb_user_zhuyao.name zhuyao_lingdao_name
        FROM
            con_department
        LEFT JOIN tb_user tb_user_zhijie ON tb_user_zhijie.uid = con_department.zhijie_lingdao
        LEFT JOIN tb_user tb_user_fenguan ON tb_user_fenguan.uid = con_department.fenguan_lingdao
        LEFT JOIN tb_user tb_user_zhuyao ON tb_user_zhuyao.uid = con_department.zhuyao_lingdao
        WHERE con_department.id = ? LIMIT 1
    `

    let res = await mysqlUtil.execute(sql, [departId])
    return res[0] || null
}

async function shangbanDetail(startTime, endTime, shangbanTime, xiabanTime, zhoumo, jiejiari) {
    let start = moment(startTime)
    let end = moment(endTime)
    let infos = []
    while(start.format('YYYY-MM-DD') != end.format('YYYY-MM-DD')) {
        let dayInfo = {
            day: start.format('YYYY-MM-DD'),
            start: start.format('YYYY-MM-DD HH:mm:ss'),
            end: start.endOf('day').format('YYYY-MM-DD HH:mm:ss')
        }
        if (moment(dayInfo.start).isBefore(moment(dayInfo.day + ' ' + shangbanTime))) {
            dayInfo.start = moment(dayInfo.day + ' ' + shangbanTime).format('YYYY-MM-DD HH:mm:ss')
        }
        if (moment(dayInfo.end).isAfter(moment(dayInfo.day + ' ' + xiabanTime))) {
            dayInfo.end = moment(dayInfo.day + ' ' + xiabanTime).format('YYYY-MM-DD HH:mm:ss')
        }
        infos.push(dayInfo)
        start = start.add(1, 'day').startOf('day')
    }
    let dayInfo = {
        day: start.format('YYYY-MM-DD'),
        start: start.format('YYYY-MM-DD HH:mm:ss'),
        end: end.format('YYYY-MM-DD HH:mm:ss')
    }
    if (moment(dayInfo.start).isBefore(moment(dayInfo.day + ' ' + shangbanTime))) {
        dayInfo.start = moment(dayInfo.day + ' ' + shangbanTime).format('YYYY-MM-DD HH:mm:ss')
    }
    if (moment(dayInfo.end).isAfter(moment(dayInfo.day + ' ' + xiabanTime))) {
        dayInfo.end = moment(dayInfo.day + ' ' + xiabanTime).format('YYYY-MM-DD HH:mm:ss')
    }
    infos.push(dayInfo)

    let detail = []
    for (let i = 0; i != infos.length; i++) {
        // 判断当天是否上班
        let r = await mysqlUtil.execute('SELECT typ FROM con_jiejiari WHERE riqi = ? LIMIT 1', [infos[i].day])
        if (r.length == 0) {
            detail.push(infos[i])
            continue
        }

        // 周末
        if (r[0].typ == 1 && zhoumo == 0) {
            continue
        }

        // 节假日
        if (r[0].typ == 2 && jiejiari == 0) {
            continue
        }

        detail.push(infos[i])
    }

    return detail
}

module.exports = {
    shangbanDetail,

    // 处理登录
    login: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        try {
            let res = await mysqlUtil.execute('SELECT name, avatar, phone, email, signimg FROM tb_user WHERE uid = ? LIMIT 1', [uid])
            if (res.length == 0) return callback({code: -1, message: '用户不存在'})

            callback({ code: 0, message: 'success', data: { userInfo: res[0] } })
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 用户信息
    userInfo: async (io, socket, params, callback) => {

        let uid = socket.uid
        logger.debug('user info entry', uid)
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        try {
            let sql = `
                SELECT
                    tb_user.uid,
                    tb_user.name,
                    tb_user.avatar,
                    tb_user.phone,
                    tb_user.email,
                    tb_user.signimg,
                    tb_user.ruzhiDate,
                    tb_user.department,
                    tb_user.position,
                    tb_user.srt,
                    con_department.name departmentName,
                    con_position.name positionName
                FROM tb_user
                INNER JOIN con_department ON tb_user.department = con_department.id
                INNER JOIN con_position ON tb_user.position = con_position.id
                WHERE tb_user.uid = ?
                LIMIT 1
            `

            let res = await mysqlUtil.execute(sql, [uid])
            if (res.length == 0) return callback({code: -1, message: '用户不存在'})
            let info = res[0]

            info.ruzhiDate = moment(info.ruzhiDate).format('YYYY-MM-DD')

            callback({code: 0, message: 'success', data: info})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 修改昵称
    modifyName: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (typeof params.phone == 'undefined' && typeof params.email == 'undefined') return callback({code: -1, message: '参数缺失'})

        try {
            if (typeof params.phone != 'undefined') {
                await mysqlUtil.execute('UPDATE tb_user SET phone = ? WHERE uid = ? LIMIT 1', [params.phone, uid])
            }
            if (typeof params.email != 'undefined') {
                await mysqlUtil.execute('UPDATE tb_user SET email = ? WHERE uid = ? LIMIT 1', [params.email, uid])
            }
            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 部门列表
    departList: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        try {
            let sql = `
                SELECT
                    con_department.id,
                    con_department.name,
                    con_department.up_department,
                    con_department.zhijie_lingdao,
                    tb_user1.name zhijie_lingdao_name,
                    con_department.fenguan_lingdao,
                    tb_user2.name fenguan_lingdao_name,
                    con_department.zhuyao_lingdao,
                    tb_user3.name zhuyao_lingdao_name,
                    IFNULL( t1.cnt, 0 ) cnt
                FROM
                    con_department
                    LEFT JOIN tb_user tb_user1 ON tb_user1.uid = con_department.zhijie_lingdao
                    LEFT JOIN tb_user tb_user2 ON tb_user2.uid = con_department.fenguan_lingdao
                    LEFT JOIN tb_user tb_user3 ON tb_user3.uid = con_department.zhuyao_lingdao
                    LEFT JOIN ( 
                            SELECT department, COUNT( 1 ) cnt FROM tb_user WHERE sta != '离职' GROUP BY department 
                        ) t1 
                        ON con_department.id = t1.department
                WHERE con_department.is_del = 0
            `
            let res = await mysqlUtil.execute(sql)
            res.sort((a, b) => { return a.srt - b.srt })
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 查看部门人员
    departMembers: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id) return callback({code: -1, message: '参数缺失'})

        try {
            let sql = `
                SELECT
                    tb_user.uid,
                    tb_user.name,
                    con_department.name departName,
                    con_position.name posName
                FROM
                    tb_user
                    INNER JOIN con_department ON con_department.id = tb_user.department
                    INNER JOIN con_position ON con_position.id = tb_user.position
                WHERE
                    tb_user.department = ? AND tb_user.sta != '离职'
            `
            let res = await mysqlUtil.execute(sql, [params.id])
            callback({code: 0, message: '', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 设置领导
    setDepartLingdao: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.departId || !params.uid) return callback({code: -1, message: '参数缺失'})

        try {
            let sql = 'UPDATE con_department SET lingdao = ? WHERE id = ? LIMIT 1'
            await mysqlUtil.execute(sql, [params.uid, params.departId])
            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 添加部门
    addDepart: async (io, socket, params, callback) => {

        if (!params.departmentName || !params.upDepart) return callback({code: -1, message: '参数缺失'})
        try {
            let sql = 'SELECT MAX(srt) msrt FROM con_department'
            let res = await mysqlUtil.execute(sql)
            let maxSrt = res[0].msrt
            await mysqlUtil.execute('INSERT INTO con_department SET ?', [{
                name: params.departmentName,
                up_department: params.upDepart,
                srt: maxSrt + 1,
                createTime: Date.now()
            }])

            // 通知刷新架构
            io.emit('REFRESH_CONTACT')

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 删除部门
    delDepart: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id) return callback({code: -1, message: '参数缺失'})
        try {
            // 判断部门下面是否存在员工
            let sql = 'SELECT 1 FROM tb_user WHERE department = ? LIMIT 1'
            let res = await mysqlUtil.execute(sql, [params.id])
            if (res.length != 0) return callback({code: -1, message: '当前部门存在员工无法删除'})

            // 判断部门下面是否有从属部门
            sql = 'SELECT 1 FROM con_department WHERE up_department = ? LIMIT 1'
            res = await mysqlUtil.execute(sql, [params.id])
            if (res.length != 0) return callback({code: -1, message: '当前部门存在从属部门无法删除'})
            await mysqlUtil.execute('UPDATE con_department SET is_del = 1 WHERE id = ? LIMIT 1', [params.id])

            // 通知刷新架构
            io.emit('REFRESH_CONTACT')

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 岗位列表
    posList: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        try {
            let sql = `
                SELECT
                    con_position.id,
                    con_position.name,
                    IFNULL( t1.cnt, 0 ) cnt
                FROM
                    con_position
                    LEFT JOIN ( 
                            SELECT position, COUNT( 1 ) cnt FROM tb_user WHERE sta != '离职' GROUP BY position 
                        ) t1 
                        ON con_position.id = t1.position
                WHERE con_position.is_del = 0
            `
            let res = await mysqlUtil.execute(sql)
            res.sort((a, b) => { return a.srt - b.srt })
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 查看岗位人员
    posMembers: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id) return callback({code: -1, message: '参数缺失'})

        try {
            let sql = `
                SELECT
                    tb_user.name,
                    con_department.name departName,
                    con_position.name posName
                FROM
                    tb_user
                    INNER JOIN con_department ON con_department.id = tb_user.department
                    INNER JOIN con_position ON con_position.id = tb_user.position
                WHERE
                    tb_user.position = ? AND tb_user.sta != '离职'
            `
            let res = await mysqlUtil.execute(sql, [params.id])
            callback({code: 0, message: '', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 添加岗位
    addPos: async (io, socket, params, callback) => {
        if (!params.positionName) return callback({code: -1, message: '参数缺失'})
        try {
            let sql = 'SELECT MAX(srt) msrt FROM con_position'
            let res = await mysqlUtil.execute(sql)
            let maxSrt = res[0].msrt
            await mysqlUtil.execute('INSERT INTO con_position SET ?', [{
                name: params.positionName,
                srt: maxSrt + 1,
                createTime: Date.now()
            }])

            // 通知刷新架构
            io.emit('REFRESH_CONTACT')

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 修改岗位名称
    modifyPosName: async (io, socket, params, callback) => {
        if (!params.id || !params.name) return callback({code: -1, message: '参数缺失'})
        try {
            await mysqlUtil.execute('UPDATE con_position SET name = ? WHERE id = ? LIMIT 1', [params.name, params.id])

            // 通知刷新架构
            io.emit('REFRESH_CONTACT')

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 删除岗位
    delPos: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id) return callback({code: -1, message: '参数缺失'})

        try {
            // 查看岗位是否存在员工
            let sql = 'SELECT 1 FROM tb_user WHERE position = ? LIMIT 1'
            let res = await mysqlUtil.execute(sql, [params.id])
            if (res.length != 0) return callback({code: -1, message: '当前岗位存在员工无法删除'})
            await mysqlUtil.execute('UPDATE con_position SET is_del = 1 WHERE id = ? LIMIT 1', [params.id])

            // 通知刷新架构
            io.emit('REFRESH_CONTACT')

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 角色列表
    roleList: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        try {
            let sql = `
                SELECT
                    con_role.id,
                    con_role.name,
                    IFNULL( t1.cnt, 0 ) cnt
                FROM
                    con_role
                    LEFT JOIN ( 
                            SELECT role, COUNT( 1 ) cnt FROM tb_user WHERE sta != '离职' GROUP BY role 
                        ) t1 
                        ON con_role.id = t1.role
                WHERE con_role.is_del = 0
            `
            let res = await mysqlUtil.execute(sql)
            res.sort((a, b) => { return a.srt - b.srt })
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 查看角色人员
    roleMembers: async (io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id) return callback({code: -1, message: '参数缺失'})

        try {
            let sql = `
                SELECT
                    tb_user.name,
                    con_department.name departName,
                    con_position.name posName,
                    con_role.name roleName
                FROM
                    tb_user
                    INNER JOIN con_department ON con_department.id = tb_user.department
                    INNER JOIN con_position ON con_position.id = tb_user.position
                    INNER JOIN con_role ON con_role.id = tb_user.role
                WHERE
                    tb_user.role = ? AND tb_user.sta != '离职'
            `
            let res = await mysqlUtil.execute(sql, [params.id])
            callback({code: 0, message: '', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 添加角色
    addRole: async (io, socket, params, callback) => {
        if (!params.roleName) return callback({code: -1, message: '参数缺失'})
        try {
            let sql = 'SELECT MAX(srt) msrt FROM con_role'
            let res = await mysqlUtil.execute(sql)
            let maxSrt = res[0].msrt
            await mysqlUtil.execute('INSERT INTO con_role SET ?', [{
                name: params.roleName,
                srt: maxSrt + 1,
                createTime: Date.now()
            }])

            // 通知刷新架构
            io.emit('REFRESH_CONTACT')

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 修改角色名称
    modifyRoleName: async (io, socket, params, callback) => {
        if (!params.id || !params.name) return callback({code: -1, message: '参数缺失'})
        try {
            await mysqlUtil.execute('UPDATE con_role SET name = ? WHERE id = ? LIMIT 1', [params.name, params.id])

            // 通知刷新架构
            io.emit('REFRESH_CONTACT')

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 删除角色
    delRole: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.id) return callback({code: -1, message: '参数缺失'})

        try {
            // 查看岗位是否存在员工
            let sql = 'SELECT 1 FROM tb_user WHERE role = ? LIMIT 1'
            let res = await mysqlUtil.execute(sql, [params.id])
            if (res.length != 0) return callback({code: -1, message: '当前角色存在员工无法删除'})
            await mysqlUtil.execute('UPDATE con_role SET is_del = 1 WHERE id = ? LIMIT 1', [params.id])

            // 通知刷新架构
            io.emit('REFRESH_CONTACT')

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 员工列表
    userList: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        logger.debug('get user list', params)

        let pageIndex = parseInt(params.pageIndex || 1);
        let pageCount = parseInt(params.pageCount || 10);
        try {
            // 查询有多少条记录
            let res = await mysqlUtil.execute('SELECT COUNT(1) cnt FROM tb_user');
            let count = res[0].cnt;
            // 查询员工信息
            let sql = `
                SELECT
                    tb_user.id,
                    tb_user.uid,
                    tb_user.name,
                    tb_user.gender,
                    tb_user.leixing,
                    tb_user.xingzhi,
                    tb_user.zhiji,
                    tb_user.upper,
                    tb_user.phone,
                    tb_user.email,
                    tb_user.sta,
                    tb_user.ruzhiDate,
                    tb_user.zhuanzhengDate,
                    tb_user.lizhiDate,
                    tb_user.department,
                    tb_user.remark,
                    tb_user.srt,
                    con_department.name departmentName,
                    tb_user.position,
                    con_position.name positionName,
                    tb_user.role,
                    con_role.name roleName
                FROM tb_user
                LEFT JOIN con_department ON tb_user.department = con_department.id
                LEFT JOIN con_position ON tb_user.position = con_position.id
                LEFT JOIN con_role ON tb_user.role = con_role.id
                WHERE 1=1 
            `
            let sqlparams = [];
            if (params.name) {
                sql += 'AND tb_user.name = ? ';
                sqlparams.push(params.name);
            }
            sql += 'LIMIT ?, ?'
            sqlparams.push((pageIndex - 1) * pageCount, pageCount)
            res = await mysqlUtil.execute(sql, sqlparams);
            // 根据员工id进行分类，部门岗位放在员工信息的属性数组中
            let userInfoMap = {}
            for (let i = 0; i != res.length; i++) {
                userInfoMap[res[i].uid] = userInfoMap[res[i].uid] || { departPoses: [] }
                userInfoMap[res[i].uid].id = res[i].id
                userInfoMap[res[i].uid].uid = res[i].uid
                userInfoMap[res[i].uid].name = res[i].name
                userInfoMap[res[i].uid].gender = res[i].gender
                userInfoMap[res[i].uid].leixing = res[i].leixing
                userInfoMap[res[i].uid].xingzhi = res[i].xingzhi
                userInfoMap[res[i].uid].zhiji = res[i].zhiji
                userInfoMap[res[i].uid].upper = res[i].upper
                userInfoMap[res[i].uid].phone = res[i].phone
                userInfoMap[res[i].uid].email = res[i].email
                userInfoMap[res[i].uid].sta = res[i].sta
                userInfoMap[res[i].uid].department = res[i].department
                userInfoMap[res[i].uid].departmentName = res[i].departmentName
                userInfoMap[res[i].uid].position = res[i].position
                userInfoMap[res[i].uid].positionName = res[i].positionName
                userInfoMap[res[i].uid].role = res[i].role
                userInfoMap[res[i].uid].roleName = res[i].roleName
                userInfoMap[res[i].uid].remark = res[i].remark
                userInfoMap[res[i].uid].srt = res[i].srt
                userInfoMap[res[i].uid].ruzhiDate = moment(res[i].ruzhiDate).format('YYYY-MM-DD')
                userInfoMap[res[i].uid].zhuanzhengDate = moment(res[i].zhuanzhengDate).format('YYYY-MM-DD')
                userInfoMap[res[i].uid].lizhiDate = moment(res[i].lizhiDate).format('YYYY-MM-DD')

            }
            // 将员工信息对象展开成数组
            let userInfoAry = []
            for (let uid in userInfoMap) {
                userInfoAry.push(userInfoMap[uid])
            }
            userInfoAry.sort((a, b) => { return b.srt - a.srt })
            callback({code: 0, message: 'success', data: {list: userInfoAry, count}})
        }
        catch (err) {
            logger.error(err);
            callback({code: -1, message: 'system error'})
        }
    },

    // 联系人列表
    contactList: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        try {
            // 查询部门列表
            let sql = `SELECT id, name FROM con_department ORDER BY srt ASC`
            let departmentList = await mysqlUtil.execute(sql)
            // 查询玩家列表
            sql = `
                SELECT
                    tb_user.uid,
                    tb_user.name,
                    tb_user.avatar,
                    tb_user.phone,
                    tb_user.department,
                    tb_user.ruzhiDate,
                    tb_user.sta,
                    tb_user.srt,
                    con_position.srt positionSrt,
                    con_position.name positionName,
                    con_department.name departmentName
                FROM tb_user
                LEFT JOIN con_department ON tb_user.department = con_department.id
                LEFT JOIN con_position ON tb_user.position = con_position.id
                WHERE
                    tb_user.sta != '离职 '
                ORDER BY con_position.srt ASC
            `
            let res = await mysqlUtil.execute(sql)
            let departmentUserMap = {}
            for (let i = 0; i != res.length; i++) {
                res[i].avatar = res[i].avatar
                departmentUserMap[res[i].department] = departmentUserMap[res[i].department] || { userList: [] }
                departmentUserMap[res[i].department].userList.push(res[i])
            }

            let list = []
            for (let i = 0; i != departmentList.length; i++) {
                departmentUserMap[departmentList[i].id] = departmentUserMap[departmentList[i].id] || { userList: [] }
                if (departmentUserMap[departmentList[i].id].userList.length == 0) continue
                departmentUserMap[departmentList[i].id].name = departmentList[i].name + '(' + departmentUserMap[departmentList[i].id].userList.length + ')'
                departmentUserMap[departmentList[i].id].departmentId = departmentList[i].id
                departmentUserMap[departmentList[i].id].userList.sort((a, b) => {
                    return b.srt - a.srt
                })
                list.push(departmentUserMap[departmentList[i].id])
            }

            callback({code: 0, message: 'success', data: list})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    addUser: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        logger.debug('add user', params)
        if (!params.uid || !params.name || !params.gender || !params.xingzhi || !params.leixing || !params.phone || !params.email || !params.sta || !params.departPoses) return callback({code: -1, message: '参数缺失1'})

        if (!Array.isArray(params.departPoses) || params.departPoses.length == 0) {
            return callback({code: -1, message: '参数错误'})
        }

        for (let i = 0; i != params.departPoses.length; i++) {
            if (!params.departPoses[i].department || !params.departPoses[i].position) {
                return callback({code: -1, message: '参数缺失2'})
            }
        }

        try {
            // 检查uid是否重复
            let uid = parseInt(params.uid)
            if (!uid || uid < 0) if (res.length != 0) return callback({code: -1, message: '工号错误'})
            let res = await mysqlUtil.execute('SELECT 1 FROM tb_user WHERE uid = ? LIMIT 1', [params.uid])
            if (res.length != 0) return callback({code: -1, message: '工号已被占用'})

            // 检查手机号码是否重复
            res = await mysqlUtil.execute('SELECT 1 FROM tb_user WHERE phone = ? LIMIT 1', [params.phone])
            if (res.length != 0) return callback({code: -1, message: '手机号码已经被使用'})

            // 检查邮箱是否重复
            res = await mysqlUtil.execute('SELECT 1 FROM tb_user WHERE email = ? LIMIT 1', [params.email])
            if (res.length != 0) return callback({code: -1, message: '邮箱已被使用'})

            // 添加新用户
            await mysqlUtil.execute('INSERT INTO tb_user SET ?', [{
                uid,
                name: params.name,
                gender: params.gender,
                xingzhi: params.xingzhi,
                leixing: params.leixing,
                upper: params.upper || 0,
                zhiji: params.zhiji,
                password: 'YCBHQ@2023zhzx',
                avatar: config.baseUrl + 'defaultavatar.png',
                phone: params.phone,
                email: params.email,
                signimg: params.signimg,
                ruzhiDate: moment(params.ruzhiDate).format('YYYY-MM-DD'),
                isNew: 1,
                department: params.departPoses[0].department,
                position: params.departPoses[0].position,
                sta: params.sta,
                remark: params.remark || '',
                srt: params.srt || 0,
                createTime: Date.now(),
                updateTime: Date.now()
            }])

            // 通知刷新架构
            io.emit('REFRESH_CONTACT')

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 员工离职
    userLizhi: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        console.log('user lizhi', params)

        if (!params.uid) return callback({code: -1, message: '参数缺失'})

        try {
            await mysqlUtil.execute('UPDATE tb_user SET sta = "离职", lizhiDate = ? WHERE uid = ? LIMIT 1', [moment().format('YYYY-MM-DD'), params.uid])

            // 通知刷新架构
            io.emit('REFRESH_CONTACT')

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 员工转正
    userZhuanzheng: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        console.log('user lizhi', params)

        if (!params.uid) return callback({code: -1, message: '参数缺失'})

        try {

            await mysqlUtil.execute('UPDATE tb_user SET sta = "在职", zhuanzhengDate = ? WHERE uid = ? LIMIT 1', [moment().format('YYYY-MM-DD'), params.uid])

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 修改密码
    modifyPwd: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        console.log('user lizhi', params)

        if (!params.uid || !params.pwd) return callback({code: -1, message: '参数缺失'})

        try {

            await mysqlUtil.execute('UPDATE tb_user SET password = ? WHERE uid = ? LIMIT 1', [params.pwd, params.uid])

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 修改用户信息
    modifyUserInfo: async (io, socket, params, callback) => {

        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        console.log('modifyUserInfo', params)

        if (!params.uid || !params.name || !params.gender || !params.phone || !params.email || !params.leixing || !params.xingzhi || !params.zhiji || !params.department || !params.position) return callback({code: -1, message: '参数缺失'})

        try {
            let sql = `
            UPDATE tb_user SET
                name = ?,
                gender = ?,
                phone = ?,
                email = ?,
                leixing = ?,
                xingzhi = ?,
                zhiji = ?,
                remark = ?,
                srt = ?,
                department = ?,
                position = ?,
                role = ?,
                upper = ?
            WHERE uid = ? LIMIT 1
            `
            await mysqlUtil.execute(sql, [params.name, params.gender, params.phone, params.email, params.leixing, params.xingzhi, params.zhiji, params.remark || '', params.srt || 0,  params.department, params.position, params.role || 0, params.upper || null, params.uid])

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 根据uid获取用户信息
    getUserInfoByUid: async(io, socket, params, callback) => {
        let uid = socket.uid
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        callback = callback || commonModule.emptyFunc

        if (!params.uid) return callback({code: -1, message: '参数缺失'})

        try {
            let sql = `
                SELECT
                    tb_user.*,
                    con_position.name positionName,
                    con_department.name departmentName
                FROM
                    tb_user
                    INNER JOIN con_position ON con_position.id = tb_user.position
                    INNER JOIN con_department ON con_department.id = tb_user.department
                WHERE
                    tb_user.uid = ?
                LIMIT 1
            `
            let res = await mysqlUtil.execute(sql, [params.uid])
            if (res.length == 0) return callback({code: -1, message: '用户不存在'})
            callback({code: 0, message: '', data: res[0]})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 根据uid获取用户部门岗位信息
    getDpInfoByUid: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.uid) return callback({code: -1, message: '参数缺失'})

        try {
            let sql = `
                SELECT
                    con_department.id,
                    con_department.name,
                    con_position.id,
                    con_position.name
                FROM tb_user_depart_pos
                INNER JOIN con_department ON tb_user_depart_pos.department = con_department.id
                INNER JOIN con_position ON tb_user_depart_pos.position = con_position.id
                WHERE tb_user_depart_pos.uid = ?
            `
            let res = await mysqlUtil.execute(sql, [params.uid])
            callback({code: 0, message: '', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 获取节假日配置
    getJiejieriConfig: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        try {
            let res = await mysqlUtil.execute('SELECT * FROM con_jiejiari')
            let jiejiariInfo = {}
            for (let i = 0; i != res.length; i++) {
                res[i].riqi = moment(res[i].riqi).format('YYYY-MM-DD')
                jiejiariInfo[res[i].riqi] = res[i]
            }

            callback({code: 0, message: '', data: jiejiariInfo})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 更新节假日配置
    updateJiejiariConfig: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.riqi) return callback({code: -1, message: '参数缺失'})

        try {
            await mysqlUtil.execute('UPDATE con_jiejiari SET typ = ? WHERE riqi = ? LIMIT 1', [params.typ || 0, params.riqi])
            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
        }
    },

    // 获取休息天的列表
    getXiuxiDayList: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        let pageIndex = parseInt(params.pageIndex || 1);
        let pageCount = parseInt(params.pageCount || 10);

        try {
            let res = await mysqlUtil.execute('SELECT COUNT(1) cnt FROM con_jiejiari')
            let count = res[0].cnt
            let sql = 'SELECT * FROM con_jiejiari LIMIT ?, ?'
            let params = [(pageIndex - 1) * pageCount, pageCount]
            res = await mysqlUtil.execute(sql, params)
            callback({code: 0, message: 'success', data: {list: res, count}})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 获取休息天的列表
    getXiuxiDayListApp: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        let nowDate = moment().format('YYYY-MM-DD')
        let endDate = moment().add(3, 'month').format('YYYY-MM-DD')

        try {
            let sql = 'SELECT * FROM con_jiejiari WHERE riqi > ? AND riqi < ? AND typ != 0'
            let params = [nowDate, endDate]
            res = await mysqlUtil.execute(sql, params)
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 添加排班
    addPaiban: async (io, socket, params, callback) => {

        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.id) return callback({code: -1, message: '参数缺失'})

        logger.debug('add paiban', params)

        let zhiban = params.zhiban || []

        try {
            params.riqi = moment(params.riqi).format('YYYY-MM-DD')

            // 删除用户排班表
            await mysqlUtil.execute('UPDATE con_jiejiari SET zhiban = ? WHERE id = ? LIMIT 1', [JSON.stringify(zhiban), params.id])

            // 三天之内的发送通知
            let thatDay = moment(params.riqi).startOf('day')
            let next3Day = moment().add(3, 'day').startOf('day')
            if (thatDay.isSameOrBefore(next3Day)) {
                // 发送排班通知 插入用户排班表
                for (let i = 0; i != zhiban.length; i++) {
                    // 插入通知
                    await mysqlUtil.execute('INSERT INTO tb_user_notification SET ?', [{
                        uid: zhiban[i].uid, // 请假人的uid
                        typ: 22,
                        title: '排班安排',
                        content: '管理员安排你在' + params.riqi + '日进行值班，请提前做好安排',
                        sta: 0,
                        resTyp: 3,
                        relevenceId: params.id,
                        createTime: Date.now()
                    }])
    
                    // 通知给请假人
                    io.in(zhiban[i].uid + '-app').emit('NOTIFICATION-CHANGE')
                    io.in(zhiban[i].uid + '-app').emit('NOTIFICATION-NEW')
                    io.in(zhiban[i].uid + '-web').emit('NOTIFICATION-CHANGE')
                    io.in(zhiban[i].uid + '-web').emit('NOTIFICATION-NEW')
                }
            }

            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    paibanDetail: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        logger.debug('paiban detail', params)
        if (!params.id || params.id == 'null') return callback({code: -1, message: '参数缺失'})

        try {
            let res = await mysqlUtil.execute('SELECT * FROM con_jiejiari WHERE id = ? LIMIT 1', [params.id])
            if (res.length == 0) return callback({code: -1, message: 'system error'})
            callback({code: 0, message: '', data: res[0]})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 排班统计 统计当前月 下一个月的数据
    paibanStatis: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        try {
            // 当前月
            let momentNow = moment()
            let currentMonth = {
                year: momentNow.get('year'),
                month: momentNow.get('month') + 1,
                userList: []
            }
            let currentMonthUserObj = {}
            let sql = 'SELECT * FROM con_jiejiari WHERE riqi >= ? AND riqi < ?'
            let res = await mysqlUtil.execute(sql, [momentNow.startOf('month').format('YYYY-MM-DD'), momentNow.endOf('month').format('YYYY-MM-DD')])
            for (let i = 0; i != res.length; i++) {
                if (res[i].zhiban) {
                    let zhiban = res[i].zhiban
                    for (let j = 0; j != zhiban.length; j++) {
                        currentMonthUserObj[zhiban[j].uid] = currentMonthUserObj[zhiban[j].uid] || {name: zhiban[j].name, cnt: 0}
                        currentMonthUserObj[zhiban[j].uid].cnt++
                    }
                }
            }
            for (let key in currentMonthUserObj) {
                currentMonth.userList.push(currentMonthUserObj[key])
            }

            // 下月
            let momentNext = moment().add(1, 'month')
            let nextMonth = {
                year: momentNext.get('year'),
                month: momentNext.get('month') + 1,
                userList: []
            }
            let nextMonthUserObj = {}
            res = await mysqlUtil.execute(sql, [momentNext.startOf('month').format('YYYY-MM-DD'), momentNext.endOf('month').format('YYYY-MM-DD')])
            for (let i = 0; i != res.length; i++) {
                if (res[i].zhiban) {
                    let zhiban = res[i].zhiban
                    for (let j = 0; j != zhiban.length; j++) {
                        nextMonthUserObj[zhiban[j].uid] = nextMonthUserObj[zhiban[j].uid] || {name: zhiban[j].name, cnt: 0}
                        nextMonthUserObj[zhiban[j].uid].cnt++
                    }
                }
            }
            for (let key in nextMonthUserObj) {
                nextMonth.userList.push(nextMonthUserObj[key])
            }

            callback({code: 0, message: 'success', data: [currentMonth, nextMonth]})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    paibanMonthDetail: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return callback({code: 9999, message: '请重新登录'})

        if (!params.year || !params.month) return callback({code: -1, message: '参数缺失'})

        try {
            let m = moment()
            m.year(params.year)
            m.month(params.month - 1)
            let monthData = []
            let res = await mysqlUtil.execute('SELECT * FROM con_jiejiari WHERE riqi >= ? AND riqi <= ?', [m.startOf('month').format('YYYY-MM-DD'), m.endOf('month').format('YYYY-MM-DD')])
            for (let i = 0; i != res.length; i++) {
                if (res[i].zhiban) {
                    let md = {date: moment(res[i].riqi).format('YYYY-MM-DD'), info: []}
                    for (let j = 0; j != res[i].zhiban.length; j++) {
                        md.info.push(res[i].zhiban[j].name)
                    }
                    monthData.push(md)
                }
            }
            callback({code: 0, message: '', data: monthData})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    chepaiList: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        try {
            let res = await mysqlUtil.execute('SELECT * FROM con_chepai')
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    deleteChepai: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.id) return callback({code: -1, message: '参数缺失'})
        try {
            await mysqlUtil.execute('DELETE FROM con_chepai WHERE id = ? LIMIT 1', [params.id])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    addChepai: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.name) callback({code: -1, message: '参数缺失'})
        try {
            await mysqlUtil.execute('INSERT INTO con_chepai SET ?', [{name: params.name}])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
        }
    },

    yinzhangList: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        try {
            let res = await mysqlUtil.execute('SELECT * FROM con_yinzhang')
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    deleteYinzhang: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.id) return callback({code: -1, message: '参数缺失'})
        try {
            await mysqlUtil.execute('DELETE FROM con_yinzhang WHERE id = ? LIMIT 1', [params.id])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    addYinzhang: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.name) callback({code: -1, message: '参数缺失'})
        try {
            await mysqlUtil.execute('INSERT INTO con_yinzhang SET ?', [{name: params.name}])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
        }
    },

    huiyishiList: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        try {
            let res = await mysqlUtil.execute('SELECT * FROM con_meetroom')
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    deleteHuiyishi: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.id) return callback({code: -1, message: '参数缺失'})
        try {
            await mysqlUtil.execute('DELETE FROM con_meetroom WHERE id = ? LIMIT 1', [params.id])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    addHuiyishi: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.name) callback({code: -1, message: '参数缺失'})
        try {
            await mysqlUtil.execute('INSERT INTO con_meetroom SET ?', [{name: params.name}])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
        }
    },

    qingjiaList: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        try {
            let res = await mysqlUtil.execute('SELECT * FROM con_qingjia')
            callback({code: 0, message: 'success', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    deleteQingjia: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.id) return callback({code: -1, message: '参数缺失'})
        try {
            await mysqlUtil.execute('DELETE FROM con_qingjia WHERE id = ? LIMIT 1', [params.id])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    addQingjia: async (io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.name) callback({code: -1, message: '参数缺失'})
        try {
            await mysqlUtil.execute('INSERT INTO con_qingjia SET ?', [{name: params.name}])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
        }
    },

    // 获取审核人
    getAuditors: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        let uidd = params.uidd || uid
        if (typeof params.typ == 'undefined') return callback({code: -1, message: '参数缺失'})

        let auditors = []

        try {
            let res = await mysqlUtil.execute('SELECT auditStep FROM con_eve WHERE eve_id = ? LIMIT 1', [params.typ])
            if (res.length == 0) return callback({code: 0, message: '', data: []})

            let lingdaos = await getLingdao(uidd)

            logger.debug('领导', lingdaos)

            let auditStep = res[0].auditStep || []
            for (let i = 0; i != auditStep.length; i++) {
                let step = auditStep[i]
                if (step.typ == 'zhijie') {
                    if (lingdaos && lingdaos.zhijie_lingdao) {
                        let sql = `
                            SELECT 
                                con_role.name
                            FROM
                                tb_user
                                LEFT JOIN con_role ON con_role.id = tb_user.role
                            WHERE
                                tb_user.uid = ?
                            LIMIT 1
                        `
                        let res = await mysqlUtil.execute(sql, [lingdaos.zhijie_lingdao])
                        auditors.push({uid: lingdaos.zhijie_lingdao, name: lingdaos.zhijie_lingdao_name, positionName: res[0].name, stepName: step.name, sta: step.sta})
                    }
                } else if (step.typ == 'fenguan') {
                    if (lingdaos && lingdaos.fenguan_lingdao) {
                        let sql = `
                            SELECT 
                                con_role.name
                            FROM
                                tb_user
                                LEFT JOIN con_role ON con_role.id = tb_user.role
                            WHERE
                                tb_user.uid = ?
                            LIMIT 1
                        `
                        let res = await mysqlUtil.execute(sql, [lingdaos.fenguan_lingdao])
                        auditors.push({uid: lingdaos.fenguan_lingdao, name: lingdaos.fenguan_lingdao_name, positionName: res[0].name, stepName: step.name, sta: step.sta})
                    }
                } else if (step.typ == 'zhuyao') {
                    if (lingdaos && lingdaos.zhuyao_lingdao) {
                        let sql = `
                            SELECT 
                                con_role.name
                            FROM
                                tb_user
                                LEFT JOIN con_role ON con_role.id = tb_user.role
                            WHERE
                                tb_user.uid = ?
                            LIMIT 1
                        `
                        let res = await mysqlUtil.execute(sql, [lingdaos.zhuyao_lingdao])
                        auditors.push({uid: lingdaos.zhuyao_lingdao, name: lingdaos.zhuyao_lingdao_name, positionName: res[0].name, stepName: step.name, sta: step.sta})
                    }
                } else if (step.typ == 'zhiding') {
                    let r = await mysqlUtil.execute(`
                            SELECT 
                                tb_user.uid,
                                tb_user.name, 
                                con_role.name positionName
                            FROM 
                                tb_user
                                LEFT JOIN con_role ON con_role.id = tb_user.role
                            WHERE tb_user.uid = ? LIMIT 1
                        `, [step.val])
                    if (r.length != 0) {
                        r[0].stepName = step.name
                        r[0].sta = step.sta
                        auditors.push(r[0])
                    }
                }
            }

            callback({code: 0, message: '', data: auditors})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    getEventConfig: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        try {
            let res = await mysqlUtil.execute('SELECT * FROM con_eve')
            callback({code: 0, message: '', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    getRootConfig: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        try {
            let res = await mysqlUtil.execute('SELECT * FROM con_root')
            for (let i = 0; i != res.length; i++) {
                // 查询权限用户名称
                let userNames = ''
                let r = await mysqlUtil.execute(`
                    SELECT
                        tb_user.name
                    FROM tb_user_root
                    INNER JOIN tb_user ON tb_user.uid = tb_user_root.uid
                    WHERE tb_user_root.rid = ?
                `, [res[i].id])
                for (let j = 0; j != r.length; j++) {
                    userNames += r[j].name
                    if (j != r.length - 1) {
                        userNames += '、'
                    }
                }
                res[i].userNames = userNames
            }
            callback({code: 0, message: '', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    getLingdao: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        let uidd = params.uid || uid

        logger.debug('get lingdao', params)

        try {
            let lingdaos = await getLingdao(uidd)

            if (lingdaos && lingdaos.zhijie_lingdao) {
                let sql = `
                    SELECT 
                        con_role.name
                    FROM
                        con_role
                        LEFT JOIN tb_user ON con_role.id = tb_user.role
                    WHERE
                        tb_user.uid = ?
                    LIMIT 1
                `
                let res = await mysqlUtil.execute(sql, [lingdaos.zhijie_lingdao])
                lingdaos.zhijie_lingdao_position_name = res[0].name
            }
            if (lingdaos && lingdaos.fenguan_lingdao) {
                let sql = `
                    SELECT 
                        con_role.name
                    FROM
                        con_role
                        LEFT JOIN tb_user ON con_role.id = tb_user.role
                    WHERE
                        tb_user.uid = ?
                    LIMIT 1
                `
                let res = await mysqlUtil.execute(sql, [lingdaos.fenguan_lingdao])
                lingdaos.fenguan_lingdao_position_name = res[0].name
            }
            if (lingdaos && lingdaos.zhuyao_lingdao) {
                let sql = `
                    SELECT 
                        con_role.name
                    FROM
                        con_role
                        LEFT JOIN tb_user ON con_role.id = tb_user.role
                    WHERE
                        tb_user.uid = ?
                    LIMIT 1
                `
                let res = await mysqlUtil.execute(sql, [lingdaos.zhuyao_lingdao])
                lingdaos.zhuyao_lingdao_position_name = res[0].name
            }
            callback({code: 0, message: '', data: lingdaos})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    getDepartmentLingdao: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        logger.debug('getDepartmentLingdao', params)
        
        if (!params.departId) return callback({code: -1, message: '参数缺失'})

        try {
            let lingdaos = await getDepartmentLingdao(params.departId)

            if (lingdaos && lingdaos.zhijie_lingdao) {
                let sql = `
                    SELECT 
                        con_role.name
                    FROM
                        con_role
                        LEFT JOIN tb_user ON con_role.id = tb_user.role
                    WHERE
                        tb_user.uid = ?
                    LIMIT 1
                `
                let res = await mysqlUtil.execute(sql, [lingdaos.zhijie_lingdao])
                lingdaos.zhijie_lingdao_position_name = res[0].name
            }
            if (lingdaos && lingdaos.fenguan_lingdao) {
                let sql = `
                    SELECT 
                        con_role.name
                    FROM
                        con_role
                        LEFT JOIN tb_user ON con_role.id = tb_user.role
                    WHERE
                        tb_user.uid = ?
                    LIMIT 1
                `
                let res = await mysqlUtil.execute(sql, [lingdaos.fenguan_lingdao])
                lingdaos.fenguan_lingdao_position_name = res[0].name
            }
            if (lingdaos && lingdaos.zhuyao_lingdao) {
                let sql = `
                    SELECT 
                        con_role.name
                    FROM
                        con_role
                        LEFT JOIN tb_user ON con_role.id = tb_user.role
                    WHERE
                        tb_user.uid = ?
                    LIMIT 1
                `
                let res = await mysqlUtil.execute(sql, [lingdaos.zhuyao_lingdao])
                lingdaos.zhuyao_lingdao_position_name = res[0].name
            }
            callback({code: 0, message: '', data: lingdaos})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    modifyZhijieLingdao: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.departId || !params.lingdaoId) return callback({code: -1, message: '参数缺失'})

        try {
            await mysqlUtil.execute('UPDATE con_department SET zhijie_lingdao = ? WHERE id = ? LIMIT 1', [params.lingdaoId, params.departId])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    modifyFenguanLingdao: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.departId || !params.lingdaoId) return callback({code: -1, message: '参数缺失'})

        try {
            await mysqlUtil.execute('UPDATE con_department SET fenguan_lingdao = ? WHERE id = ? LIMIT 1', [params.lingdaoId, params.departId])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    modifyZhuyaoLingdao: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.lingdaoId) return callback({code: -1, message: '参数缺失'})

        try {
            await mysqlUtil.execute('UPDATE con_department SET zhuyao_lingdao = ?', [params.lingdaoId])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },


    modifyDepartment: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        logger.debug('modify department', params)

        if (!params.id || !params.name || !params.zhijielingdaoId || !params.fenguanlingdaoId || !params.zhuyaolingdaoId) {
            return callback({code: -1, message: '参数缺失'})
        }

        try {
            let sql = 'UPDATE con_department SET name = ?, zhijie_lingdao = ?, fenguan_lingdao = ?, zhuyao_lingdao = ? WHERE id = ? LIMIT 1'
            await mysqlUtil.execute(sql, [params.name, params.zhijielingdaoId, params.fenguanlingdaoId, params.zhuyaolingdaoId, params.id])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    saveAuditStep: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        logger.debug('modify department', params)

        if (!params.id || !params.steps) return  callback({code: -1, message: '参数缺失'})

        try {
            let sql = 'UPDATE con_eve SET auditStep = ? WHERE id = ? LIMIT 1'
            await mysqlUtil.execute(sql, [JSON.stringify(params.steps), params.id])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    saveChengbanStep: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        logger.debug('modify department', params)

        if (!params.id || !params.steps) return  callback({code: -1, message: '参数缺失'})

        try {
            let sql = 'UPDATE con_eve SET chengbanStep = ? WHERE id = ? LIMIT 1'
            await mysqlUtil.execute(sql, [JSON.stringify(params.steps), params.id])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    setPermissionUsers: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        logger.debug('setPermissionUsers', params)

        if (!params.id || !params.users || !Array.isArray(params.users)) return callback({code: -1, message: '参数缺失'})

        try {
            // 先删除权限的其它人
            await mysqlUtil.execute('DELETE FROM tb_user_root WHERE rid = ?', [params.id])
            for (let i = 0; i != params.users.length; i++) {
                await mysqlUtil.execute('INSERT INTO tb_user_root SET ?', [{
                    rid: params.id,
                    uid: params.users[i]
                }])
            }
            callback({code: 0, message: 'success'})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    getAllUsers: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        try {
            let res = await mysqlUtil.execute('SELECT * FROM tb_user WHERE sta != "离职" ORDER BY uid ASC')
            callback({code: 0, message: '', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    getUserPermissionsApp: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        try {
            let sql = `
                SELECT
                    con_root.appflag
                FROM tb_user_root
                INNER JOIN con_root ON con_root.id = tb_user_root.rid
                WHERE tb_user_root.uid = ?
            `
            let res = await mysqlUtil.execute(sql, [uid])
            let permissions = []
            for (let i = 0; i != res.length; i++) {
                if (res[i].appflag) {
                    permissions.push(res[i].appflag)
                }
            }
            callback({code: 0, message: '', data: permissions})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    getUserPermissionsWeb: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        try {
            let sql = `
                SELECT
                    con_root.webflag
                FROM tb_user_root
                INNER JOIN con_root ON con_root.id = tb_user_root.rid
                WHERE tb_user_root.uid = ?
            `
            let res = await mysqlUtil.execute(sql, [uid])
            let permissions = []
            for (let i = 0; i != res.length; i++) {
                if (res[i].webflag) {
                    permissions.push(res[i].webflag)
                }
            }
            callback({code: 0, message: '', data: permissions})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    getPermissionsUsers: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.id) return callback({code: -1, message: '参数缺失'})

        try {
            let sql = 'SELECT uid FROM tb_user_root WHERE rid = ?'
            let res = await mysqlUtil.execute(sql, [params.id])
            let uids = []
            for (let i = 0; i != res.length; i++) {
                uids.push(res[i].uid)
            }
            callback({code: 0, message: '', data: uids})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    getUserGroupList: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        try {
            let res = await mysqlUtil.execute('SELECT * FROM con_user_group')
            for (let i = 0; i != res.length; i++) {
                let userInfoList = []
                let names = ''
                let userlist = res[i].userlist
                for (let j = 0; j != userlist.length; j++) {
                    let r = await mysqlUtil.execute('SELECT uid, name FROM tb_user WHERE uid = ? LIMIT 1', [userlist[j]])
                    userInfoList.push(r[0])
                    names += r[0].name
                    if (j != userlist.length -1) names += '、'
                }
                res[i].userInfoList = userInfoList
                res[i].names = names
            }
            callback({code: 0, message: '', data: res})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    addUserGroup: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.name || !params.userlist) return callback({code: -1, message: '参数缺失'})

        try {
            await mysqlUtil.execute('INSERT INTO con_user_group SET ?', [{
                name: params.name,
                userlist: JSON.stringify(params.userlist)
            }])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    delUserGroup: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.id) return callback({code: -1, message: '参数缺失'})

        try {
            await mysqlUtil.execute('DELETE FROM con_user_group WHERE id = ? LIMIT 1', [params.id])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    modifyUserGroup: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.id || !params.name || !params.userlist) return callback({code: -1, message: '参数缺失'})

        try {
            await mysqlUtil.execute('UPDATE con_user_group SET name = ?, userlist = ? WHERE id = ? LIMIT 1', [params.name, JSON.stringify(params.userlist), params.id])
            callback({code: 0, message: ''})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 催办
    cuiban: async(io, socket, params, callback) => {
        callback = callback || commonModule.emptyFunc
        let uid = params.uid
        let processName = params.processName
        let processStatus = params.processStatus
        if (!uid || !processName || !processStatus) return callback({code: -1, message: '参数缺失'})

        utils.sendReminderSmsToUser(uid, processName, processStatus)
        callback({code: 0, message: ''})
    },

    getShangbanDetail: async(io, socket, params, callback) => {
        let uid = socket.uid
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.startTime || !params.endTime) return callback({code: -1, message: '参数缺失'})

        if (!moment(params.startTime).isValid() || !moment(params.endTime).isValid()) return callback({code: -1, message: '参数错误'})

        if (moment(params.startTime).valueOf()  > moment(params.endTime).valueOf()) return callback({code: -1, message: '参数错误'})

        params.jiejiari = params.jiejiari || 0 // 是否忽略节假日
        params.zhoumo = params.zhoumo || 0 // 是否忽略周末

        logger.debug('shangban detail', params)

        try {
            // 获取考勤设置
            let sql = 'SELECT val FROM con_system_param WHERE name = "KAOQIN_SHEZHI" LIMIT 1'
            let res = await mysqlUtil.execute(sql)
            if (res.length == 0) {
                return callback({code: -1, message: '未配置考勤设置'})
            }

            let kaoqinSetting = JSON.parse(res[0].val)
            let shangbanTime = kaoqinSetting.shangbanTime + ':00'
            let xiabanTime = kaoqinSetting.xiabanTime + ':00'

            // let start = moment(params.startTime)
            // let end = moment(params.endTime)
            // let infos = []
            // while(start.format('YYYY-MM-DD') != end.format('YYYY-MM-DD')) {
            //     let dayInfo = {
            //         day: start.format('YYYY-MM-DD'),
            //         start: start.format('YYYY-MM-DD HH:mm:ss'),
            //         end: start.endOf('day').format('YYYY-MM-DD HH:mm:ss')
            //     }
            //     if (moment(dayInfo.start).isBefore(moment(dayInfo.day + ' ' + shangbanTime))) {
            //         dayInfo.start = moment(dayInfo.day + ' ' + shangbanTime).format('YYYY-MM-DD HH:mm:ss')
            //     }
            //     if (moment(dayInfo.end).isAfter(moment(dayInfo.day + ' ' + xiabanTime))) {
            //         dayInfo.end = moment(dayInfo.day + ' ' + xiabanTime).format('YYYY-MM-DD HH:mm:ss')
            //     }
            //     infos.push(dayInfo)
            //     start = start.add(1, 'day').startOf('day')
            // }
            // let dayInfo = {
            //     day: start.format('YYYY-MM-DD'),
            //     start: start.format('YYYY-MM-DD HH:mm:ss'),
            //     end: end.format('YYYY-MM-DD HH:mm:ss')
            // }
            // if (moment(dayInfo.start).isBefore(moment(dayInfo.day + ' ' + shangbanTime))) {
            //     dayInfo.start = moment(dayInfo.day + ' ' + shangbanTime).format('YYYY-MM-DD HH:mm:ss')
            // }
            // if (moment(dayInfo.end).isAfter(moment(dayInfo.day + ' ' + xiabanTime))) {
            //     dayInfo.end = moment(dayInfo.day + ' ' + xiabanTime).format('YYYY-MM-DD HH:mm:ss')
            // }
            // infos.push(dayInfo)

            // let detail = []
            // for (let i = 0; i != infos.length; i++) {
            //     // 判断当天是否上班
            //     let r = await mysqlUtil.execute('SELECT typ FROM con_jiejiari WHERE riqi = ? LIMIT 1', [infos[i].day])
            //     if (r.length == 0) {
            //         detail.push(infos[i])
            //         continue
            //     }

            //     // 周末
            //     if (r[0].typ == 1 && params.zhoumo == 0) {
            //         continue
            //     }

            //     // 节假日
            //     if (r[0].typ == 2 && params.jiejiari == 0) {
            //         continue
            //     }

            //     detail.push(infos[i])
            // }

            detail = await shangbanDetail(params.startTime, params.endTime, shangbanTime, xiabanTime, params.zhoumo, params.jiejiari)

            callback({code: 0, message: '', data: detail})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    },

    // 获取日程
    getSchedule: async(io, socket, params, callback) => {
        let uid = parseInt(socket.uid)
        callback = callback || commonModule.emptyFunc
        if (!uid) return  callback({code: 9999, message: '请重新登录'})

        if (!params.date) return callback({code: -1, message: '参数缺失'})

        if (!moment(params.date).isValid()) return callback({code: -1, message: '参数错误'})

        let dateStr = params.date
        let startMillli = moment(dateStr).startOf('day').valueOf()
        let endMilli = moment(dateStr).endOf('day').valueOf()
        let shangwuStart = moment(dateStr + ' 09:00:00').valueOf()
        let shangwuEnd = moment(dateStr + ' 12:00:00').valueOf()
        let xiawuStart = moment(dateStr + ' 12:00:00').valueOf()
        let xiawuEnd = moment(dateStr + ' 17:00:00').valueOf()

        // dailyDay: 上午； dailyType:会议；dailyTheme：主题；dailyTime：开始时间-结束时间； dailyPlace：地点

        try {
            let all = []
            // 查询会议通知记录
            // let sql = 'SELECT * FROM tb_meeting_room_apply WHERE startTime >= ? AND startTime <= ? AND JSON_CONTAINS(attenders, JSON_OBJECT("uid", ?)) AND sta = 1'
            let sql = 'SELECT * FROM tb_huiyi_tongzhi WHERE meetingDate = ? AND JSON_CONTAINS(attenders, JSON_OBJECT("uid", ?)) AND sta = 1'
            let params = [dateStr, uid]
            let res = await mysqlUtil.execute(sql, params)
            if (res.length > 0) {
                let huiyi = res[0]
                let huiyiStart = `${dateStr} ${huiyi.startTime}:00`
                logger.debug('huiyi start', huiyiStart)
                let wu = '上午'
                if (moment(huiyiStart).hour() >= 12) {
                    wu = '下午'
                }
                all.push({
                    dailyDay: wu,
                    dailyType: '会议',
                    dailyTheme: huiyi.topic,
                    dailyTime: huiyi.startTime + '-' + huiyi.endTime,
                    dailyPlace: huiyi.place
                })
            }

            // 查询接待陪同记录 查询这个用户所有的陪同记录 再筛选时间
            res = await mysqlUtil.execute('SELECT * FROM tb_user_jiedai_apply WHERE JSON_CONTAINS(peitongrenyuan, JSON_OBJECT("uid", ?)) AND sta = 1', [uid])
            logger.debug('peitong renyuan', res)
            for (let i = 0; i != res.length; i++) {

                let noon = dateStr + ' 00:00:00'
                let noonMilli = moment(noon).valueOf()
                logger.debug('noon milli', noonMilli)
                if (noonMilli >= res[i].startTime && noonMilli <= res[i].endTime) {
                    let timeStr = moment(shangwuStart).format('HH:mm') + '-' + moment(shangwuEnd).format('HH:mm')
                    all.push({
                        dailyDay: '上午',
                        dailyType: '接待',
                        dailyTheme: res[i].reason,
                        dailyTime: timeStr,
                        dailyPlace: '--'
                    })

                    timeStr = moment(xiawuStart).format('HH:mm') + '-' + moment(xiawuEnd).format('HH:mm')
                    all.push({
                        dailyDay: '下午',
                        dailyType: '接待',
                        dailyTheme: res[i].reason,
                        dailyTime: timeStr,
                        dailyPlace: '--'
                    })
                }
            }

            // 值班 去节假日表中查询
            res = await mysqlUtil.execute('SELECT * FROM con_jiejiari WHERE riqi = ? LIMIT 1', [dateStr])
            if (res.length > 0) {
                let jiejiariInfo = res[0]
                let zhiban = jiejiariInfo.zhiban || []
                let found = false
                for (let i = 0; i != zhiban.length; i++) {
                    if (zhiban[i].uid == uid) {
                        found = true
                        break
                    }
                }

                if (found) {
                    let timeStr = moment(shangwuStart).format('HH:mm') + '-' + moment(shangwuEnd).format('HH:mm')
                    all.push({
                        dailyDay: '上午',
                        dailyType: '值班',
                        dailyTheme: '值班',
                        dailyTime: timeStr,
                        dailyPlace: '--'
                    })

                    timeStr = moment(xiawuStart).format('HH:mm') + '-' + moment(xiawuEnd).format('HH:mm')
                    all.push({
                        dailyDay: '下午',
                        dailyType: '值班',
                        dailyTheme: '值班',
                        dailyTime: timeStr,
                        dailyPlace: '--'
                    })
                }
            }

            res = await mysqlUtil.execute('SELECT * FROM tb_user_daka WHERE uid = ? AND day = ? LIMIT 1', [uid, dateStr])
            if (res.length == 1) {
                let dakaInfo = res[0]

                // 出差
                if (dakaInfo.chuchaiInfo) {
                    let chuchaiId = dakaInfo.chuchaiInfo.id
                    let dest = ''
                    if (chuchaiId) {
                        let res = await mysqlUtil.execute('SELECT * FROM tb_user_chuchai_apply WHERE id = ? LIMIT 1', [chuchaiId])
                        if (res.length == 1) {
                            dest = res[0].destination
                        }
                    }
                    let timeStr = moment(shangwuStart).format('HH:mm') + '-' + moment(shangwuEnd).format('HH:mm')
                    all.push({
                        dailyDay: '上午',
                        dailyType: '出差',
                        dailyTheme: '出差',
                        dailyTime: timeStr,
                        dailyPlace: dest
                    })

                    timeStr = moment(xiawuStart).format('HH:mm') + '-' + moment(xiawuEnd).format('HH:mm')
                    all.push({
                        dailyDay: '下午',
                        dailyType: '出差',
                        dailyTheme: '出差',
                        dailyTime: timeStr,
                        dailyPlace: dest
                    })
                }

                // 加班
                if (dakaInfo.jiabanInfo) {
                    // 判断是否在上午区间内
                    if (shangwuStart >= moment(dakaInfo.jiabanInfo.start).valueOf() && shangwuEnd <= moment(dakaInfo.jiabanInfo.end).valueOf()) {
                        let timeStr = moment(shangwuStart).format('HH:mm') + '-' + moment(shangwuEnd).format('HH:mm')
                        all.push({
                            dailyDay: '上午',
                            dailyType: '加班',
                            dailyTheme: '--',
                            dailyTime: timeStr,
                            dailyPlace: '--'
                        })
                    } else if (moment(dakaInfo.jiabanInfo.start).valueOf() > shangwuStart && shangwuEnd <= moment(dakaInfo.jiabanInfo.end).valueOf()) {
                        let timeStr = moment(moment(dakaInfo.jiabanInfo.start).valueOf()).format('HH:mm') + '-' + moment(shangwuEnd).format('HH:mm')
                        all.push({
                            dailyDay: '上午',
                            dailyType: '加班',
                            dailyTheme: '--',
                            dailyTime: timeStr,
                            dailyPlace: '--'
                        })
                    } else if (moment(dakaInfo.jiabanInfo.start).valueOf() > shangwuStart && moment(dakaInfo.jiabanInfo.end).valueOf() < shangwuEnd) {
                        let timeStr = moment(moment(dakaInfo.jiabanInfo.start).valueOf()).format('HH:mm') + '-' + moment(moment(dakaInfo.jiabanInfo.end).valueOf()).format('HH:mm')
                        all.push({
                            dailyDay: '上午',
                            dailyType: '加班',
                            dailyTheme: '--',
                            dailyTime: timeStr,
                            dailyPlace: '--'
                        })
                    }
                    
                    // 判断是否在下午区间
                    if (xiawuStart >= moment(dakaInfo.jiabanInfo.start).valueOf() && xiawuEnd <= moment(dakaInfo.jiabanInfo.end).valueOf()) {
                        let timeStr = moment(xiawuStart).format('HH:mm') + '-' + moment(xiawuEnd).format('HH:mm')
                        all.push({
                            dailyDay: '下午',
                            dailyType: '加班',
                            dailyTheme: '--',
                            dailyTime: timeStr,
                            dailyPlace: '--'
                        })
                    } else if (moment(dakaInfo.jiabanInfo.start).valueOf() > xiawuStart && xiawuEnd <= moment(dakaInfo.jiabanInfo.end).valueOf()) {
                        let timeStr = moment(moment(dakaInfo.jiabanInfo.start).valueOf()).format('HH:mm') + '-' + moment(xiawuEnd).format('HH:mm')
                        all.push({
                            dailyDay: '下午',
                            dailyType: '加班',
                            dailyTheme: '--',
                            dailyTime: timeStr,
                            dailyPlace: '--'
                        })
                    } else if (moment(dakaInfo.jiabanInfo.start).valueOf() > xiawuStart && moment(dakaInfo.jiabanInfo.end).valueOf() < xiawuEnd) {
                        let timeStr = moment(moment(dakaInfo.jiabanInfo.start).valueOf()).format('HH:mm') + '-' + moment(moment(dakaInfo.jiabanInfo.end).valueOf()).format('HH:mm')
                        all.push({
                            dailyDay: '下午',
                            dailyType: '加班',
                            dailyTheme: '--',
                            dailyTime: timeStr,
                            dailyPlace: '--'
                        })
                    }
                }

                // 请假
                if (dakaInfo.qingjiaInfo) {
                    // 判断是否在上午区间内
                    if (shangwuStart >= moment(dakaInfo.qingjiaInfo.start).valueOf() && shangwuEnd <= moment(dakaInfo.qingjiaInfo.end).valueOf()) {
                        let timeStr = moment(shangwuStart).format('HH:mm') + '-' + moment(shangwuEnd).format('HH:mm')
                        all.push({
                            dailyDay: '上午',
                            dailyType: '请假',
                            dailyTheme: '--',
                            dailyTime: timeStr,
                            dailyPlace: '--'
                        })
                    } else if (moment(dakaInfo.qingjiaInfo.start).valueOf() > shangwuStart && shangwuEnd <= moment(dakaInfo.qingjiaInfo.end).valueOf()) {
                        let timeStr = moment(moment(dakaInfo.qingjiaInfo.start).valueOf()).format('HH:mm') + '-' + moment(shangwuEnd).format('HH:mm')
                        all.push({
                            dailyDay: '上午',
                            dailyType: '请假',
                            dailyTheme: '--',
                            dailyTime: timeStr,
                            dailyPlace: '--'
                        })
                    } else if (moment(dakaInfo.qingjiaInfo.start).valueOf() > shangwuStart && moment(dakaInfo.qingjiaInfo.end).valueOf() < shangwuEnd) {
                        let timeStr = moment(moment(dakaInfo.qingjiaInfo.start).valueOf()).format('HH:mm') + '-' + moment(moment(dakaInfo.qingjiaInfo.end).valueOf()).format('HH:mm')
                        all.push({
                            dailyDay: '上午',
                            dailyType: '请假',
                            dailyTheme: '--',
                            dailyTime: timeStr,
                            dailyPlace: '--'
                        })
                    }
                    
                    // 判断是否在下午区间
                    if (xiawuStart >= moment(dakaInfo.qingjiaInfo.start).valueOf() && xiawuEnd <= moment(dakaInfo.qingjiaInfo.end).valueOf()) {
                        let timeStr = moment(xiawuStart).format('HH:mm') + '-' + moment(xiawuEnd).format('HH:mm')
                        all.push({
                            dailyDay: '下午',
                            dailyType: '请假',
                            dailyTheme: '--',
                            dailyTime: timeStr,
                            dailyPlace: '--'
                        })
                    } else if (moment(dakaInfo.qingjiaInfo.start).valueOf() > xiawuStart && xiawuEnd <= moment(dakaInfo.qingjiaInfo.end).valueOf()) {
                        let timeStr = moment(moment(dakaInfo.qingjiaInfo.start).valueOf()).format('HH:mm') + '-' + moment(xiawuEnd).format('HH:mm')
                        all.push({
                            dailyDay: '下午',
                            dailyType: '请假',
                            dailyTheme: '--',
                            dailyTime: timeStr,
                            dailyPlace: '--'
                        })
                    } else if (moment(dakaInfo.qingjiaInfo.start).valueOf() > xiawuStart && moment(dakaInfo.qingjiaInfo.end).valueOf() < xiawuEnd) {
                        let timeStr = moment(moment(dakaInfo.qingjiaInfo.start).valueOf()).format('HH:mm') + '-' + moment(moment(dakaInfo.qingjiaInfo.end).valueOf()).format('HH:mm')
                        all.push({
                            dailyDay: '下午',
                            dailyType: '请假',
                            dailyTheme: '--',
                            dailyTime: timeStr,
                            dailyPlace: '--'
                        })
                    }
                }
            }

            // console.log('richeng all: ', all)
            callback({code: 0, message: '', data: all})
        } catch (err) {
            logger.error(err)
            callback({code: -1, message: 'system error'})
        }
    }
}
